class MySingleLinkedList {
    static class ListNode {
        public int val;
        public ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }

    public ListNode head;//代表链表的头结点

    public void display() {
        ListNode cur = head;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();
    }

    public void display(ListNode newHead) {
        ListNode cur = newHead;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();
    }

    public void addFirst(int val) {
        ListNode node = new ListNode(val);
        node.next = head;
        head = node;
    }
}

public class Demo2_8 {
    public static MySingleLinkedList.ListNode getIntersectionNode(MySingleLinkedList.ListNode headA,
                                                                  MySingleLinkedList.ListNode headB) {
        // 1. 假设A链表长
        MySingleLinkedList.ListNode p1 = headA;
        MySingleLinkedList.ListNode p2 = headB;
        int lenA = 0;
        int lenB = 0;
        while (p1 != null) {
            lenA++;
            p1 = p1.next;
        }
        while (p2 != null) {
            lenB++;
            p2 = p2.next;
        }
        // 给p1和p2重新赋值
        p1 = headA;
        p2 = headB;
        int len = lenA - lenB;
        // 2. 判断len是正数还是负数
        if (len < 0) {
            p1 = headB;
            p2 = headA;
            len = lenB - lenA;
        }
        // p1一定指向最长的链表 p2一定指向最短链表
        // len一定是正数
        // 3. 让p1走差值len步
        while (len != 0) {
            p1 = p1.next;
            len--;
        }
        // 4. p1和p2一起走，直到它们俩相遇
        while (p1 != p2) {
            p1 = p1.next;
            p2 = p2.next;
        }
        if (p1 == null) {
            return null;
        }
        return p1;
    }

    public static void createCut(MySingleLinkedList.ListNode headA,
                                 MySingleLinkedList.ListNode headB) {
        headA.next.next = headB.next.next;
    }

    public static void main(String[] args) {
        //相交链表
        //给你两个单链表的头节点 headA 和 headB ，
        //  请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点，返回 null 。
        MySingleLinkedList msl1 = new MySingleLinkedList();
        msl1.addFirst(1);
        msl1.addFirst(6);
        msl1.addFirst(3);
        MySingleLinkedList msl2 = new MySingleLinkedList();
        msl2.addFirst(1);
        msl2.addFirst(8);
        msl2.addFirst(10);
        msl2.addFirst(25);
        msl2.addFirst(100);
        createCut(msl1.head, msl2.head);
        //msl1.display();
        //msl2.display();
        MySingleLinkedList.ListNode ret = getIntersectionNode(msl1.head, msl2.head);
        System.out.println(ret.val);
    }

}
